
package galaxy.app.dispatch.executor;

import java.util.List;

import galaxy.app.Galaxy;
import galaxy.app.dispatch.disruptor.MessageThread;
import galaxy.app.network.rpc.packet.RequestPacket;
import galaxy.app.network.session.NettySession;
import galaxy.app.route.RouteInfo;
import galaxy.app.route.RouteSystem;

/**
 */
public class RequestPacketExecutor implements BaseExecutor {

    NettySession session;
    RequestPacket packet;

    RouteSystem route;

    public RequestPacketExecutor( NettySession session, RequestPacket packet) {
        this.session = session;
        this.packet = packet;

        route = Galaxy.systems().get(RouteSystem.class);
    }

    @Override
    public int threadId() {
        return route.getThreadId(packet.route);
    }

    @Override
    public int calcHash(List<MessageThread> list) {
        // 确保同个包(uid),最终落在同个线程执行，避免互斥
        RouteInfo routeInfo = route.getRouteInfo(packet.route);
        long hash = routeInfo.instance.getThreadHash(session, packet);
        return (int) (hash % list.size());
    }

    @Override
    public void invoke() {
        RouteInfo routeInfo = route.getRouteInfo(packet.route);
        routeInfo.instance.onReceive(session, packet);
    }
}
